var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bannerRouter = require('./routes/banner');
var orderRouter = require('./routes/order');
var proRouter = require('./routes/pro');
var adminRouter = require('./routes/admin');

var proApi = require('./api/pro');
var userApi = require('./api/user');
var orderApi = require('./api/order');
var bannerApi = require('./api/banner');
var addressApi = require('./api/address');
var searchApi = require('./api/search');
var cartApi = require('./api/cart');
var collectApi = require('./api/collect');

var app = express();

// 配置cors信息,允许所有来源的数据请求
app.all("*",(req,res,next)=>{
	// 允许所有来源
	res.header("Access-Control-Allow-Origin","*");
	// 允许的请求方式
	res.header("Access-Control-Allow-Methods","GET, POST");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , token');
	
	next();
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false ,limit:"10MB"}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api/pro', proApi);
app.use('/api/user', userApi);
app.use('/api/order', orderApi);
app.use('/api/banner', bannerApi);
app.use('/api/address', addressApi);
app.use('/api/search', searchApi);
app.use('/api/cart', cartApi);
app.use('/api/collect', collectApi);


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/banner', bannerRouter);
app.use('/order', orderRouter);
app.use('/pro', proRouter);
app.use('/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
